/**
 * AI 辅助调整组件
 */

import React, { useState } from 'react';
import { Bot, Send, Lightbulb, History, Loader2, CheckCircle, Clock, Undo2, XCircle } from 'lucide-react';
import { useProofMapper } from '@/contexts/ProofMapper';
import { showMessage } from '@/components/common/MessageTip';
import { aiQuickSuggestions } from '@/mockData/ProofMapper';
import type { AIAdjustmentCommand } from '@/types/ProofMapper';

interface AIAssistantProps {
  className?: string;
}

const AIAssistant: React.FC<AIAssistantProps> = ({ className = '' }) => {
  const {
    aiInputValue,
    adjustmentCommands,
    evaluationItems,
    selectedItems,
    setAiInput,
    addAdjustmentCommand,
    updateAdjustmentCommand,
    applyUserInput,
    rollback,
  } = useProofMapper();

  const [isProcessing, setIsProcessing] = useState(false);

  // 处理AI指令执行（改为后端会话applyUserInput）
  const handleExecuteCommand = async (command: string) => {
    if (!command.trim()) {
      showMessage('warning', '请输入调整指令');
      return;
    }

    setIsProcessing(true);
    try {
      // 记录一次发送（用于本地历史视觉反馈，可选）
      const pending: AIAdjustmentCommand = {
        id: `cmd-${Date.now()}`,
        command: command.trim(),
        type: 'modify',
        executed: false,
        created_at: new Date().toISOString(),
      };
      addAdjustmentCommand(pending);

      // 构建包含选中评估项完整数据结构的输入
      let fullInput = command.trim();
      if (selectedItems.length > 0) {
        const selectedFullItems = evaluationItems
          .filter(item => selectedItems.includes(item.id))
          .map(({ selected, updated_at, ...rest }) => rest);
        const selectedJson = JSON.stringify(selectedFullItems, null, 2);
        fullInput = `${command.trim()}\n\n用户已选择的评估项（完整数据结构，JSON）：\n${selectedJson}`;
      }

      const ok = await applyUserInput(fullInput);
      if (ok) {
        // 标记执行完成
        addAdjustmentCommand({ ...pending, executed: true, result: '已应用到清单' });
        setAiInput('');
        showMessage('success', 'AI 调整已应用');
      } else {
        showMessage('error', 'AI 调整失败，请重试');
      }
    } catch (error) {
      showMessage('error', 'AI 调整发生异常');
      console.error('AI adjustment error:', error);
    } finally {
      setIsProcessing(false);
    }
  };

  // 处理快速建议点击
  const handleQuickSuggestion = (suggestion: string) => {
    setAiInput(suggestion);
  };

  // 处理发送指令
  const handleSendCommand = () => {
    handleExecuteCommand(aiInputValue);
  };

  // 处理键盘事件
  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendCommand();
    }
  };

  // 获取指令状态图标
  const getCommandStatusIcon = (command: AIAdjustmentCommand) => {
    if (command.rolledBack) {
      return <XCircle className="h-4 w-4 text-red-500" />;
    }
    if (!command.executed) {
      return <Clock className="h-4 w-4 text-orange-500" />;
    }
    return <CheckCircle className="h-4 w-4 text-green-500" />;
  };

  // 撤销上一步
  const handleRollback = async () => {
    setIsProcessing(true);
    try {
      const ok = await rollback();
      if (ok) {
        // 找到最后一条已执行的命令并标记为已撤销
        const lastExecutedCommand = adjustmentCommands
          .slice()
          .reverse()
          .find(cmd => cmd.executed && !cmd.rolledBack);
        
        if (lastExecutedCommand) {
          updateAdjustmentCommand(lastExecutedCommand.id, {
            rolledBack: true,
            result: '已撤销'
          });
        }
        
        showMessage('success', '已撤销上一步修改');
      } else {
        showMessage('warning', '无法撤销（可能未创建会话或无可撤销记录）');
      }
    } catch (e) {
      showMessage('error', '撤销失败');
    } finally {
      setIsProcessing(false);
    }
  };

  return (
    <div className={`space-y-6 ${className}`}>
      {/* AI 辅助调整区 */}
      <div className="bg-white/80 dark:bg-card backdrop-blur-sm rounded-lg border border-border p-6">
        <div className="flex items-center gap-3 mb-4">
          <div className="flex items-center justify-center w-10 h-10 bg-blue-500/10 rounded-lg">
            <Bot className="h-5 w-5 text-blue-500" />
          </div>
          <div>
            <h2 className="text-lg font-semibold text-foreground">AI 辅助调整区</h2>
            <p className="text-sm text-muted-foreground">
              使用自然语言指令让AI调整清单
            </p>
          </div>
        </div>

        {/* 快速操作 */}
        <div className="mb-4">
          <div className="flex items-center gap-2 mb-2">
            <Lightbulb className="h-4 w-4 text-orange-500" />
            <span className="text-sm font-medium text-foreground">快速操作</span>
          </div>
          <div className="flex flex-wrap gap-2">
            {aiQuickSuggestions.map((suggestion, index) => (
              <button
                key={index}
                onClick={() => handleQuickSuggestion(suggestion)}
                className="px-3 py-1 text-xs bg-muted text-muted-foreground rounded-full hover:bg-muted/80 transition-colors"
              >
                {suggestion}
              </button>
            ))}
          </div>
        </div>

        {/* 自定义指令输入 */}
        <div className="mb-4">
          <label className="block text-sm font-medium text-foreground mb-2">
            自定义指令
          </label>
          <div className="flex gap-2">
            <textarea
              value={aiInputValue}
              onChange={(e) => setAiInput(e.target.value)}
              onKeyPress={handleKeyPress}
              placeholder="请输入您的调整指令，例如：合并所有日志类材料、增加数据传输环节的加密要求..."
              rows={3}
              className="flex-1 px-3 py-2 bg-background border border-input rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-ring resize-none"
              disabled={isProcessing}
            />
            <button
              onClick={handleSendCommand}
              disabled={isProcessing || !aiInputValue.trim()}
              className="px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
            >
              {isProcessing ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : (
                <Send className="h-4 w-4" />
              )}
              执行
            </button>
          </div>
        </div>

        {/* 操作按钮：撤销 */}
        <div className="flex items-center gap-3 mt-2">
          <button
            onClick={handleRollback}
            disabled={isProcessing}
            className="inline-flex items-center gap-2 px-3 py-2 text-sm bg-muted text-foreground rounded-md hover:bg-muted/80 disabled:opacity-50"
          >
            <Undo2 className="h-4 w-4" /> 撤销上一步
          </button>
        </div>

        {/* 使用提示 */}
        <div className="bg-muted/50 rounded-lg p-3">
          <p className="text-sm text-muted-foreground mb-2">
            <strong>使用提示：</strong>
          </p>
          <ul className="text-xs text-muted-foreground space-y-1">
            <li>• 可以要求合并、删除或修改特定的评估项目</li>
            <li>• 可以按类型或重要性对项目进行重新排序</li>
            <li>• 可以要求添加特定的安全要求或检查点</li>
            <li>• 支持批量操作，如"删除所有备注为空的项目"</li>
          </ul>
        </div>
      </div>

      {/* 调整历史 */}
      {adjustmentCommands.length > 0 && (
        <div className="bg-white/80 dark:bg-card backdrop-blur-sm rounded-lg border border-border p-6">
          <div className="flex items-center gap-3 mb-4">
            <History className="h-5 w-5 text-muted-foreground" />
            <h3 className="text-lg font-semibold text-foreground">调整历史</h3>
          </div>

          <div className="space-y-3">
            {adjustmentCommands.slice(-5).reverse().map((command: AIAdjustmentCommand) => (
              <div
                key={command.id}
                className="flex items-start gap-3 p-3 bg-muted/25 rounded-lg"
              >
                <div className="flex-shrink-0 mt-0.5">
                  {getCommandStatusIcon(command)}
                </div>
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-medium text-foreground mb-1">
                    {command.command}
                  </p>
                  {command.result && (
                    <p className="text-xs text-muted-foreground mb-2">
                      {command.result}
                    </p>
                  )}
                  <div className="flex items-center gap-2 text-xs text-muted-foreground">
                    <span>{new Date(command.created_at).toLocaleString()}</span>
                    <span>•</span>
                    <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${
                      command.rolledBack
                        ? 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200'
                        : command.executed 
                          ? 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200'
                          : 'bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-200'
                    }`}>
                      {command.rolledBack ? '已撤销' : command.executed ? '已执行' : '处理中'}
                    </span>
                  </div>
                </div>
              </div>
            ))}
          </div>

          {adjustmentCommands.length > 5 && (
            <div className="text-center mt-4">
              <button className="text-sm text-primary hover:text-primary/80 transition-colors">
                查看更多历史记录
              </button>
            </div>
          )}
        </div>
      )}

    </div>
  );
};

export default AIAssistant;
